import tkinter as tk
from tkinter import ttk, messagebox

from utils import printer_util


class ConfigurePrinterDialog(tk.Toplevel):
    def __init__(self, parent, config_manager, file_types=None):
        super().__init__(parent)
        self.title("全局打印配置")
        self.geometry("600x500")  # 增加窗口大小以容纳更多控件
        self.transient(parent)
        self.grab_set()

        self.config_manager = config_manager
        self.global_config = self.config_manager.get_global_config()

        # 添加双面打印选项映射
        self.duplex_modes = {
            "单面打印": 0,
            "双面打印(长边翻转)": 1,
            "双面打印(短边翻转)": 2,
        }

        # 如果没有提供特定文件类型，则使用默认列表
        if file_types is None:
            self.available_file_types = [
                ".pdf",
                ".doc",
                ".docx",
                ".xls",
                ".xlsx",
                ".ppt",
                ".pptx",
                ".jpg",
                ".png",
            ]
        else:
            # 确保包含"default"选项
            self.available_file_types = file_types

        # 存储每个文件类型的控件变量
        self.control_vars = {}

        self.setup_ui()
        self.load_config()

    def setup_ui(self):
        main_frame = ttk.Frame(self, padding="15")
        main_frame.pack(fill=tk.BOTH, expand=True)

        # 创建Notebook (Tab控件)
        self.tab_control = ttk.Notebook(main_frame)
        self.tab_control.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)

        # 为每种文件类型创建Tab
        self.tabs = {}
        for file_type in self.available_file_types:
            tab = ttk.Frame(self.tab_control, padding="10")
            self.tabs[file_type] = tab
            display_name = "默认配置" if file_type == "default" else f"{file_type} 文件"
            self.tab_control.add(tab, text=display_name)

            # 为每个Tab创建控件
            self.create_tab_content(tab, file_type)

        # 按钮框架
        btn_frame = ttk.Frame(main_frame)
        btn_frame.pack(fill=tk.X, pady=10)

        ttk.Button(btn_frame, text="保存配置", command=self.save_config).pack(
            side=tk.LEFT, padx=10
        )
        ttk.Button(btn_frame, text="取消", command=self.destroy).pack(
            side=tk.LEFT, padx=10
        )

        # 绑定Tab切换事件
        self.tab_control.bind("<<NotebookTabChanged>>", self.on_tab_changed)

    def create_tab_content(self, parent, file_type):
        # 存储当前文件类型的控件变量
        self.control_vars[file_type] = {}

        # 纸张大小
        ttk.Label(parent, text="纸张大小:").grid(
            row=0, column=0, padx=5, pady=8, sticky=tk.W
        )
        paper_size_var = tk.StringVar()
        paper_size = ttk.Combobox(
            parent,
            textvariable=paper_size_var,
            values=list(printer_util.PAPER_SIZES.keys()),
            state="readonly",
        )
        paper_size.grid(row=0, column=1, padx=5, pady=8, sticky=tk.EW)
        self.control_vars[file_type]["paper_size"] = paper_size_var

        # 页面方向
        ttk.Label(parent, text="页面方向:").grid(
            row=1, column=0, padx=5, pady=8, sticky=tk.W
        )
        orientation_var = tk.StringVar()
        orientation = ttk.Combobox(
            parent,
            textvariable=orientation_var,
            values=list(printer_util.ORIENTATIONS.keys()),
            state="readonly",
        )
        orientation.grid(row=1, column=1, padx=5, pady=8, sticky=tk.EW)
        self.control_vars[file_type]["orientation"] = orientation_var

        # 打印质量
        ttk.Label(parent, text="打印质量:").grid(
            row=2, column=0, padx=5, pady=8, sticky=tk.W
        )
        quality_var = tk.StringVar()
        quality = ttk.Combobox(
            parent,
            textvariable=quality_var,
            values=list(printer_util.QUALITIES.keys()),
            state="readonly",
        )
        quality.grid(row=2, column=1, padx=5, pady=8, sticky=tk.EW)
        self.control_vars[file_type]["quality"] = quality_var

        # 单双面打印
        ttk.Label(parent, text="单双面打印:").grid(
            row=3, column=0, padx=5, pady=8, sticky=tk.W
        )
        duplex_var = tk.StringVar()
        duplex = ttk.Combobox(
            parent,
            textvariable=duplex_var,
            values=list(self.duplex_modes.keys()),
            state="readonly",
        )
        duplex.grid(row=3, column=1, padx=5, pady=8, sticky=tk.EW)
        self.control_vars[file_type]["duplex"] = duplex_var

        # 打印份数
        ttk.Label(parent, text="打印份数:").grid(
            row=4, column=0, padx=5, pady=8, sticky=tk.W
        )
        copies_var = tk.StringVar(value="1")
        copies = ttk.Entry(parent, textvariable=copies_var)
        copies.grid(row=4, column=1, padx=5, pady=8, sticky=tk.EW)
        self.control_vars[file_type]["copies"] = copies_var

        # 设置列权重使控件可以扩展
        parent.columnconfigure(1, weight=1)

        # 如果是默认配置，禁用所有控件
        if file_type == "default":
            paper_size.config(state="disabled")
            orientation.config(state="disabled")
            quality.config(state="disabled")
            duplex.config(state="disabled")
            copies.config(state="disabled")

    def get_current_file_type(self):
        """获取当前选中的Tab对应的文件类型"""
        current_tab_index = self.tab_control.index(self.tab_control.select())
        return self.available_file_types[current_tab_index]

    def load_config(self):
        """加载所有文件类型的配置"""
        for file_type in self.available_file_types:
            config = self.global_config.get(file_type, {})

            # 设置控件值
            self.control_vars[file_type]["paper_size"].set(
                config.get("paper_size", "A4")
            )
            self.control_vars[file_type]["orientation"].set(
                config.get("orientation", "纵向")
            )
            self.control_vars[file_type]["quality"].set(config.get("quality", "中"))
            self.control_vars[file_type]["duplex"].set(config.get("duplex", "单面打印"))
            self.control_vars[file_type]["copies"].set(str(config.get("copies", 1)))

    def on_tab_changed(self, event):
        """当Tab切换时更新状态显示"""
        current_file_type = self.get_current_file_type()
        # 可以在这里添加其他Tab切换时需要执行的逻辑

    def save_config(self):
        """保存所有文件类型的配置"""
        success = True

        for file_type in self.available_file_types:
            # 跳过默认配置的保存
            if file_type == "default":
                continue

            try:
                copies = int(self.control_vars[file_type]["copies"].get())
                if copies < 1:
                    raise ValueError
            except ValueError:
                messagebox.showerror(
                    "输入错误", f"{file_type} 文件类型的打印份数必须是大于0的整数。"
                )
                success = False
                continue

            config = {
                "paper_size": self.control_vars[file_type]["paper_size"].get(),
                "orientation": self.control_vars[file_type]["orientation"].get(),
                "quality": self.control_vars[file_type]["quality"].get(),
                "duplex": self.control_vars[file_type]["duplex"].get(),
                "copies": copies,
            }

            if not self.config_manager.update_global_config(file_type, config):
                messagebox.showerror(
                    "错误", f"保存 {file_type} 文件类型的配置失败，请检查日志。"
                )
                success = False

        if success:
            messagebox.showinfo("成功", "所有文件类型的打印配置已保存。")
            self.global_config = self.config_manager.get_global_config()  # 更新本地配置
            self.destroy()
